package cn.fl.system.service.impl;

import java.util.ArrayList;
import java.util.List;

import cmm.comm.facade.framework.condition.SysRegionQueryCondition;
import cmm.comm.facade.framework.dto.SysRegionDTO;
import cmm.user.facade.system.api.ISysOrgRegRApiService;
import cmm.user.facade.system.condition.SysOrgRegRQC;
import cmm.user.facade.system.constant.SysResourceConstant;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.system.service.ISysOrgRegRService;
import cn.fl.system.service.ISysRegionService;
import cn.fl.system.transform.SysOrgRegRVOTransform;
import cn.fl.system.vo.SysOrgRegRVO;
import cn.fl.system.vo.SysRegionVO;
import fl.spl.facade.framework.constant.SplSystemConstant;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cmm.user.facade.system.dto.SysOrgRegRDTO;
import cn.cmm.base.framework.constant.BaseExceptionConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cmm.mid.core.framework.page.Pager;


/**
 * @Description: 组织架构-区域信息关系表 客户端服务层接口实现
 * @Description: 业务层方法名称前缀：新增：add* 删除：remove* 修改：modify* 查询对象：select* get* 批量：batch* 查询集合：search*
 */
@Service
public class SysOrgRegRServiceImpl implements ISysOrgRegRService {

	/**
	 * 日志
	 */
	private static final Logger logger = LoggerFactory.getLogger(SysOrgRegRServiceImpl.class);
	
	/**
	 * 自定义 API 自行注入需要的API服务
	 */
	@Autowired
	private ISysOrgRegRApiService sysOrgRegRApiService ;

	@Autowired
	private ISysRegionService sysRegionService ;

	@Override
	public SysOrgRegRVO selectById(Long id) throws BaseException{
		if(StringUtils.isEmpty(id)){
			BaseLogUtils.info(logger, "selectById", "主键参数不能为空!", CurrentThreadContext.getCurrentUserName());
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600, "获取对象主键不能为空!");
		}
		//TODO 业务逻辑
		SysOrgRegRDTO dto = null;//this.自定义ApiService.selectSysOrgRegRDTOById(id);
		return SysOrgRegRVOTransform.toVO(dto);
	}

	@Override
	public Long add(SysOrgRegRVO entity) throws BaseException{
		if(null == entity){
			BaseLogUtils.info(logger, "add", "新增对象不存在!");
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600,"新增对象不存在!");
		};
		//return this.sysOrgRegRApiService.add(SysOrgRegRVOTransform.toDTO(entity));
		//TODO 业务逻辑
		return null;
	}

	@Override
	public boolean removeById(Long id) throws BaseException{
		if(StringUtils.isEmpty(id)){
			BaseLogUtils.info(logger, "removeById", "删除对象主键不能为空!");
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600,"删除对象主键不能为空!");
		};
		//return this.sysOrgRegRApiService.removeSysOrgRegRDTOById(id);
		//TODO 业务逻辑
		return false;
	}
	
	/**
     * 删除
     * @param ids
     * @return
     */
    public boolean removeByIds(List<Long> ids)throws BaseException{
		if(CollectionUtils.isEmpty(ids)){
			BaseLogUtils.info(logger, "removeByIds", "删除主键参数集合不能为空!", CurrentThreadContext.getCurrentUserName());
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600,"删除对象主键不能为空!");
		}
		return false;
    }

	@Override
	public boolean modify(SysOrgRegRVO entity) throws BaseException{
		if(null == entity){
			BaseLogUtils.info(logger, "modify", "修改对象不能为空!");
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600,"修改对象不能为空!");
		}
		//return this.sysOrgRegRApiService.modifySysOrgRegRDTO(SysOrgRegRVOTransform.toDTO(entity));
		//TODO 业务逻辑
		return false;
	}

	@Override
	public Pager searchListPage(Pager page) throws BaseException{
		if(null == page){
			page = new Pager();
		}
		//return this.sysOrgRegRApiService.searchSysOrgRegRListPage(page);
		//TODO 业务逻辑
		return null;
	}

	@Override
	public JSONObject searchRegionsByOrgId(Long orgId) throws BaseException {
		JSONObject jsonObject = new JSONObject();
		SysOrgRegRQC sysOrgRegRQC = null ;
		List<Long> regionIds = null ;
		if(StringUtils.isNotEmpty(orgId)){
			sysOrgRegRQC = new SysOrgRegRQC();
			sysOrgRegRQC.setOrgId(orgId);
			List<SysOrgRegRVO> regRVOList = this.searchOrgRegRByQC(sysOrgRegRQC);
			if(CollectionUtils.isEmpty(regRVOList)){
				BaseLogUtils.info(logger,"searchRegionsByOrgId","区域数据为空！操作人："+CurrentThreadContext.getCurrentUserName());
				//return jsonObject;
			}
			if(CollectionUtils.isNotEmpty(regRVOList)){
				BaseLogUtils.info(logger,"searchRegionsByOrgId","区域数据DATA>>"+ com.alibaba.fastjson.JSONObject.toJSONString(regRVOList)+",操作人："+CurrentThreadContext.getCurrentUserName());
				regionIds = new ArrayList<>(regRVOList.size());
				for(SysOrgRegRVO sysOrgRegRVO : regRVOList){
					regionIds.add(sysOrgRegRVO.getRgnId());
				}
			}
		}
		JSONArray jsonArray = this.searchOrgRegRTree(regionIds, null);
		jsonObject.put("data", jsonArray);
		if(CollectionUtils.isNotEmpty(regionIds)){
			jsonObject.put("IDs", JSONArray.fromObject(regionIds));
		}else{
			jsonObject.put("IDs", new JSONArray());
		}
		return jsonObject;
	}

	/**
	 * 根据条件查询组织架构与区域关系
	 * @param sysOrgRegRQC
	 * @return
	 * @throws BaseException
	 */
	@Override
	public List<SysOrgRegRVO> searchOrgRegRByQC(SysOrgRegRQC sysOrgRegRQC) throws BaseException {
		return SysOrgRegRVOTransform.toVOList(this.sysOrgRegRApiService.searchOrgRegRListByQC(sysOrgRegRQC));
	}

	/**
	 * 根据条件模糊查询树
	 */
	@Override
	public JSONArray searchOrgRegRTree(List<Long> ids ,SysRegionQueryCondition condition) throws BaseException {
		if(condition == null){
			JSONArray jsonArray = this.searchTreeIsCheckById(ids);
			return jsonArray;
		}
		if(StringUtils.isEmpty(condition.getRgnLvlMax())){
			condition.setRgnLvlMax(2);
		}
		List<SysRegionDTO> searchRegRListByRegNm = this.sysRegionService.searchOrgRegRListByRegNm(condition, SplSystemConstant.FL_SYS_CD);
		if(CollectionUtils.isEmpty(searchRegRListByRegNm)){
			return new JSONArray();
		}

		JSONArray jsonArray = new JSONArray();
		for (SysRegionDTO sysRegionDTO : searchRegRListByRegNm) {
			JSONObject obj = new JSONObject();
			Long id = sysRegionDTO.getId();
			if(CollectionUtils.isNotEmpty(ids) && ids.contains(id)){
				obj.put("ischecked", true);
			}else{
				obj.put("ischecked", false);
			}
			obj.put("id", sysRegionDTO.getId());
			obj.put("text", sysRegionDTO.getRgnNm());
			obj.put("pid", sysRegionDTO.getRgnPid());
			obj.put("iconClass", "");
			jsonArray.add(obj);
		}
		JSONArray treeMenuList = treeMenuList(jsonArray, SysResourceConstant.SYS_RES_CD_PID_INIT);
		return treeMenuList;
	}

	/**
	 * 授权
	 * @param orgId
	 * @param sysOrgRegRVOs
	 * @return
	 * @throws BaseException
	 */
	@Override
	public boolean addOrgRegionR(Long orgId, List<SysOrgRegRVO> sysOrgRegRVOs) throws BaseException {
		if(StringUtils.isEmpty(orgId) && CollectionUtils.isEmpty(sysOrgRegRVOs)){
			BaseLogUtils.info(logger, "addOrgRegionR", "授权失败,组织架构ID与组织架构区域关系都为空.", CurrentThreadContext.getCurrentUserName());
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600,BaseExceptionConstant.BASE_EXCEPTION_CODE_600_NAME);
		}
		return this.sysOrgRegRApiService.addSysOrgRegR(orgId, SysOrgRegRVOTransform.toDTOList(sysOrgRegRVOs), CurrentThreadContext.getCurrentSysCd());
	}

	@Override
	public JSONArray searchTreeIsCheckById(List<Long> ids) throws BaseException {
		JSONArray jsonArray = new JSONArray ();
		List<SysRegionDTO> sysResInitList = this.sysRegionService.searchSysRegionByPid(SysResourceConstant.SYS_RES_CD_PID_INIT,CurrentThreadContext.getCurrentSysCd());
		JSONArray jsonArrayRes = setValueToArray(sysResInitList, jsonArray, ids);
		return jsonArrayRes;
	}

	/**
	 * 递归添加整个集合数据
	 * @param treeList
	 * @param parentId
	 * @return
	 */
	public JSONArray treeMenuList(JSONArray treeList, Long parentId) {
		JSONArray childMenu = new JSONArray();
		for (Object object : treeList) {
			JSONObject jsonMenu = JSONObject.fromObject(object);
			long oid = jsonMenu.getLong("id");
			long pid = jsonMenu.getLong("pid");
			if (parentId == pid) {
				JSONArray c_node = treeMenuList(treeList, oid);
				jsonMenu.put("children", c_node);
				childMenu.add(jsonMenu);
			}
		}
		return childMenu;
	}

	/**
	 * 关联递归添加方法
	 */
	private JSONArray setValueToArray(List<SysRegionDTO> list,JSONArray array,List<Long> regRList){

		if(CollectionUtils.isNotEmpty(list)){
			for (SysRegionDTO sysRegionDTO : list) {
				Long id = sysRegionDTO.getId();
				JSONObject jsonObject = new JSONObject ();
				if(CollectionUtils.isNotEmpty(regRList) && regRList.contains(id)){
					jsonObject.put("ischecked", true);
				}else{
					jsonObject.put("ischecked", false);
				}
				jsonObject.put("id",id );
				jsonObject.put("text",sysRegionDTO.getRgnNm());
				/*if(StringUtils.isNotEmpty(sysRegionDTO.getResImg())){
					jsonObject.put("iconClass", sysRegionDTO.getResImg());
				}*/
				jsonObject.put("iconClass", "");
				List<SysRegionDTO> childrenList = this.sysRegionService.searchSysRegionByPid(id,CurrentThreadContext.getCurrentSysCd());
				if(CollectionUtils.isNotEmpty(childrenList)){
					JSONArray jsonArray2 = setValueToArray(childrenList, new JSONArray(),regRList);
					jsonObject.put("children",jsonArray2);
				}
				array.add(jsonObject);

			}
		}
		return array;
	}
}
